package com.dbappsecurity.network.client.interceptor;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Arirus on 2017/8/11.
 */

public final class HeaderInterceptor implements Interceptor {
  private Headers.Builder mBuilder;

  private InterceptorHelper.ModifyParms modifyParms = null;

  public void setModifyParms(InterceptorHelper.ModifyParms modifyParms){
    this.modifyParms = modifyParms;
  }

  public HeaderInterceptor() {
    mBuilder = InterceptorHelper.defaultHeader();
  }

  @Override
  public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();
    if (this.mBuilder == null) {
      this.mBuilder = new Headers.Builder();
    }

    if (modifyParms !=null){
      Map<String , String> map = modifyParms.modify(new HashMap<String, String>());
      for (String key:map.keySet()) {
        this.mBuilder.set(key,map.get(key));
      }
    }else {
      if (InterceptorHelper.TokenWrapper.INSTANCE.getToken() != null) {
        this.mBuilder.set("Authorization",
            "Bearer " + InterceptorHelper.TokenWrapper.INSTANCE.getToken());
      }
    }
    Request compressedRequest = originalRequest.newBuilder().headers(this.mBuilder.build()).build();
    return chain.proceed(compressedRequest);
  }
}
